import React, {useEffect, useState} from "react";
import {makeStyles} from "@material-ui/core/styles";
import {CircularProgress, Fab, Grid, Tab, Tabs, Tooltip, Typography, Zoom} from "@material-ui/core";
import Result from "./ResultDetails/ResultDetails";
import {useDispatch, useSelector} from "react-redux";
import {
  getAllFilterData,
  getAnalysisMethods,
  selectDeselectActivityName,
  setActivityAttributes,
  setTimeDuration
} from "../../../../../../redux/reducers/editor";
import TimeFilter from "./TimeFilter/TimeFilter";
import UserFilter from "./UserFilter/UserFilter";
import IconButton from "@material-ui/core/IconButton";
import HelpIcon from "@material-ui/icons/Help";
import RefreshIcon from "@material-ui/icons/Refresh";
import {scrollToTop} from "../../../../../../assets/functions/functions";
import {attributeDataFunction} from "../Analysis/attributeData";
import Button from "@material-ui/core/Button";
import WidgetsIcon from '@material-ui/icons/Widgets';
import ScheduleIcon from '@material-ui/icons/Schedule';
import PeopleIcon from '@material-ui/icons/People';
import MenuMultiSelect from "../../../Common/MenuMultiSelect/MenuMultiSelect";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    marginBottom: theme.spacing(2)
  },
  tabs: {
    borderBottom: `1px solid ${theme.palette.divider}`,
    overflow: "visible"
  },
  gutterTop: {
    paddingTop: theme.spacing(2)
  },
  buttonSpacing: {
    marginRight: theme.spacing(1)
  },
  gutterBottom: {
    marginBottom: theme.spacing(2)
  },
  helper: {
    cursor: "pointer",
    marginLeft: theme.spacing(2)
  }
}));

export default function Filters(props) {
  // Props
  const {classes, handleStepBackward, handleStepForward} = props;

  // Constants from Redux store
  const activityNameData = useSelector(state => state.editor.fetchedData.activityName);
  const activityExtensionData = useSelector(state => state.editor.fetchedData.activityExtensionId);
  const contextActivitiesData = useSelector(state => state.editor.fetchedData.contextActivities);
  const resultData = useSelector(state => state.editor.fetchedData.result);
  const selectedPlatform = useSelector(state => state.editor.selectedData.platforms);
  const selectedActivityTypes = useSelector(state => state.editor.selectedData.activityTypes);
  const selectedActionOnActivities = useSelector(state => state.editor.selectedData.actionOnActivities);
  const selectedActivityName = useSelector(state => state.editor.selectedData.activityName);
  const selectedActivityExtensionData = useSelector(state => state.editor.selectedData.activityExtensionId);
  const selectedContextActivities = useSelector(state => state.editor.selectedData.contextActivities);
  const selectedAnalysisMethod = useSelector(state => state.editor.selectedData.analysisMethod);
  const selectedResult = useSelector(state => state.editor.selectedData.result);
  const timeDurationData = useSelector(state => state.editor.selectedData.timeDuration);
  const languages = useSelector(state => state.editor.fetchedData.language);

  // Local constants
  const dispatch = useDispatch();
  const styles = useStyles();
  let date = new Date();
  let dateEnd = new Date();
  let dateStart = new Date(date.setDate(date.getDate() - 7));
  const [value, setValue] = useState(0);
  const errorActionOnActivity = useSelector(state => state.errorMessages.connectionErrors.actionOnActivity);

  useEffect(() => {
    scrollToTop();
    if (timeDurationData.startDate === "" && timeDurationData.endDate === "")
      dispatch(setTimeDuration(dateStart, dateEnd));
    if (selectedActivityName.length === 0) {
      dispatch(getAllFilterData(selectedPlatform, selectedActivityTypes, selectedActionOnActivities, languages));
    }
  }, [dispatch])

  const handleChangeFilters = (event, newValue) => {
    setValue(newValue);
  };

  // Activity names
  const handleSelectActivityName = (event, values) => {
    dispatch(selectDeselectActivityName(values));
  };

  const handleSelectAllActivityNames = () => {
    dispatch(selectDeselectActivityName(activityNameData));
  }

  const continueToAnalysisMethods = () => {
    dispatch(setActivityAttributes(attributeDataFunction(resultData)));
    if (selectedAnalysisMethod.length === 0)
      dispatch(getAnalysisMethods());
    handleStepForward();
    scrollToTop();
  }

  return (
    <>
      <Grid container direction="column" md={9} lg={8} xl={6}>
        <Grid item xs className={styles.root}>
          <Tabs indicatorColor="primary" className={styles.tabs} textColor="primary" variant="fullWidth" value={value}
                onChange={handleChangeFilters}>
            <Tab label="Activities" icon={<WidgetsIcon/>}/>
            <Tab label="Timeframe" icon={<ScheduleIcon/>}/>
            <Tab label="Users" icon={<PeopleIcon/>}/>
          </Tabs>
        </Grid>
        <Grid container direction="column">
          {activityNameData.length !== 0 || selectedActivityName.length !== 0 ? (
            <>
              {value === 0 ? (
                <>
                  <Grid item xs className={styles.gutterBottom}>
                    <MenuMultiSelect
                      name={"List of Activities"}
                      dataSource={activityNameData}
                      itemName={selectedActivityName}
                      selectAll={handleSelectAllActivityNames}
                      handleChange={handleSelectActivityName}
                    />
                  </Grid>
                  {/*<Grid item xs>*/}
                  {/*  <Divider/>*/}
                  {/*</Grid>*/}
                  {resultData.length !== 0 ?
                    // GRADED ACTIVITY: ACTIVITIES THAT COMES WITH SCORING
                    <Grid container className={classes.gutterTop}>
                      <Grid container justify="space-between" alignItems="center">
                        <Grid item xs>
                          <Typography >Select the <b>Outcomes</b> of the <b>selected
                            activities</b></Typography>
                        </Grid>
                        <Grid item>
                          <Tooltip TransitionComponent={Zoom} arrow placement="right" title={
                            <>
                              <Typography  gutterBottom>
                                These are grades/scores/outcomes of the activities
                              </Typography>
                              <Typography  gutterBottom>
                                <li>
                                  <b>Raw:</b> This is the actual score earned by a student in an activity such as
                                  a <b><i>Quiz</i></b>.
                                </li>
                              </Typography>
                              <Typography  gutterBottom>
                                <li>
                                  <b>Max:</b> This is the maximum score, a student can achieve in an activity. For
                                  example, <b><i>100</i></b> can be the maximum score a student can earn in
                                  a <b><i>Quiz</i></b>.
                                </li>
                              </Typography>
                              <Typography  gutterBottom>
                                <li>
                                  <b>Scaled:</b> This is the ratio of <b><i>Raw</i></b> score to
                                  the <b><i>Max</i></b> score for that particular activity. For example,
                                  the <b><i>Raw</i></b> for a <b><i>Quiz</i></b> earned by a student
                                  is <b><i>80</i></b>, and the <b><i>Max</i></b> score
                                  is <b><i>100.</i></b> Therefore, <b><i>Scaled</i></b> score
                                  will be <b><i>0.8</i></b>.
                                </li>
                              </Typography>
                              <Typography  gutterBottom>
                                <li>
                                  <b>Response:</b> This will show of all the answers that students have used as an
                                  answer to a question in an activity.
                                </li>
                              </Typography>
                            </>
                          }>
                            <IconButton> <HelpIcon/> </IconButton>
                          </Tooltip>
                        </Grid>
                      </Grid>
                      <Grid item xs>
                        <Result
                          resultData={resultData}
                          selectedResult={selectedResult}
                          classes={classes}
                          styles={styles}
                        />
                      </Grid>
                    </Grid> : <></>}
                  {/* Advanced Filters */}
                  {/*
                    {activityExtensionData.length !== 0 ?
                      // ACTIVITY FEATURES: THE EXTENSION/FEATURES OF THE ACTIVITY NAME SELECTED ABOVE
                      <Grid container>
                        <Grid container justify="space-between" alignItems="center">
                          <Grid item xs>
                            <Typography >
                              What are the <b>Additional Features</b> available that defines the selected
                              activities?
                            </Typography>
                          </Grid>
                          <Grid item>
                            <Tooltip TransitionComponent={Zoom} arrow placement="right" title={
                              <>
                                <Typography  gutterBottom>
                                  The activities chosen from <b><i>What?</i></b> question provides a list of
                                  features
                                  for individual activities.
                                </Typography>
                                <Typography >
                                  This dropdown menu consists of a list of all the features that defines the
                                  activity. Selecting specific features allows you to filter the activity based on
                                  the
                                  requirements for your analysis. It can have important information such as
                                  the <b><i>quiz
                                  number, course name</i></b> etc.
                                </Typography>
                              </>
                            }>
                              <IconButton> <HelpIcon/> </IconButton>
                            </Tooltip>
                          </Grid>
                        </Grid>
                        <Grid item xs>
                          <ActivityDetails activityExtensionData={activityExtensionData}
                                           selectedActivityExtensionData={selectedActivityExtensionData}
                                           classes={classes}
                                           styles={styles}/>
                        </Grid>
                      </Grid> : <></>}
                    {contextActivitiesData.length !== 0 ?
                      // CONTEXT ACTIVITIES: ACTIVITIES THAT ARE RELATED TO THE SELECTED ACTIVITIES
                      <Grid container className={classes.gutterTop}>
                        <Grid container justify="space-between" alignItems="center">
                          <Grid item xs>
                            <Typography >
                              Select <b>Related Activities</b>
                            </Typography>
                          </Grid>
                          <Grid item>
                            <Tooltip TransitionComponent={Zoom} arrow placement="right" title={
                              <>
                                <Typography  gutterBottom>
                                  Other activities can have direct and indirect relations to an activity.
                                </Typography>
                                <Typography  gutterBottom>
                                  <li><b>Parent:</b> An activity that has a direct relation. For example,
                                    a <b><i>Quiz</i></b> can have many <b><i>Questions</i></b>, which
                                    means, that <b><i>Quiz</i></b> would be the parent of
                                    a <b><i>Question</i></b>.
                                  </li>
                                </Typography>
                                <Typography  gutterBottom>
                                  <li><b>Grouping:</b> An activity that has an indirect relationship with the
                                    activity
                                    selected. For example, a <b><i>Quiz</i></b> can be the parent of
                                    a <b><i>Question</i></b>, and a <b><i>Course</i></b> can be a parent of
                                    a <b><i>Quiz</i></b>. Therefore, <b><i>Course</i></b> will belong to
                                    the <b><i>Grouping </i></b> category of the <b><i>Question</i></b>.
                                  </li>
                                </Typography>
                              </>
                            }>
                              <IconButton> <HelpIcon/> </IconButton>
                            </Tooltip>
                          </Grid>
                        </Grid>
                        <Grid item xs>
                          <ContextDetails
                            contextActivitiesData={contextActivitiesData} classes={classes}
                            selectedContextActivities={selectedContextActivities} styles={styles}/>
                        </Grid>
                      </Grid> : <></>}
                      */}
                </>
              ) : value === 1 ?
                <>
                  <Typography className={styles.gutterBottom}>
                    The Timeframe allows to specify a duration period of the activities.
                  </Typography>

                  <TimeFilter timeDurationData={timeDurationData}/>
                </>
                :
                <>
                  <Typography className={styles.gutterBottom}>
                    The User Filter allows to specify the list of user(s) for your analysis.
                  </Typography>

                  <UserFilter/>
                </>
              }
            </>
          ) : !errorActionOnActivity ? (
            <Grid container direction="column" alignItems="center">
              <CircularProgress className={classes.gutterTopBottom}/>
              <Typography variant="overline">Loading filter data</Typography>
            </Grid>
          ) : (
            <Grid container justify="center" alignItems="center">
              <Fab color="primary" size="small" className={classes.gutterRight}
                   onClick={dispatch(getAllFilterData(selectedPlatform, selectedActivityTypes, selectedActionOnActivities, languages))}>
                <RefreshIcon/>
              </Fab>
              <Grid item>
                <Typography>Connection problem, please retry</Typography>
              </Grid>
            </Grid>
          )}
        </Grid>


        <Grid container>
          <Button onClick={handleStepBackward} className={styles.buttonSpacing} aria-label="Back">
            Back
          </Button>

          <Button variant="contained" color="primary" aria-label="Next" disabled={selectedActivityName.length === 0}
                  onClick={continueToAnalysisMethods}>
            Next
          </Button>
        </Grid>
      </Grid>
    </>
  );
}
